<template>
  <div>
    <template v-if="formData.length">
      <div class="form-content" v-for="(item, index) in formData" :key="index">
        <div class="btn-danger" v-if="dialogType === 'edit'">
          <el-button type="text" size="small" icon="el-icon-delete" @click="handleDelete(index)" class="btn-del" v-if="dialogType !== 'batch'">删 除 </el-button>
        </div>
        <div class="rules-content">
          <avue-form ref="warehousePropertiesForm" v-model="formData[index]" :option="rulesOption" class="rules-form">
            <template slot-scope="{}" slot="scheme">
              <el-input placeholder="请选择业务规则分类" readonly="true" v-model="formData[index].scheme" disabled>
                <el-button slot="append" icon="el-icon-search" @click="openRulesModel(index)"></el-button>
              </el-input>
            </template>
            <template slot-scope="{}" slot="ruleContainer">
              <h3>规则内容</h3>
            </template>
            <template slot-scope="{}" slot="overlimitRate">
              <div>
                <el-radio v-model="formData[index].constraintOperator" disabled label="=">不限制</el-radio>
                <el-radio v-model="formData[index].constraintOperator" disabled label=">"
                  >允许超出
                  <el-input style="width: 40%" disabled v-model="formData[index].constraintValue" type="number" min="1" placeholder=""></el-input>
                  %</el-radio
                >
              </div>
            </template>
            <!--先进先出规则-->
            <template slot-scope="{}" slot="fifoRequiredLabel">
              <el-tooltip class="item" effect="dark" content="根据物料生产日期控制出库顺序" placement="top-start">
                <i class="el-icon-info"></i>
              </el-tooltip>
              <span>管控先进先出:</span>
            </template>
            <!--超领规则-->
            <template slot-scope="{}" slot="isAllowOverreceiveLabel">
              <el-tooltip class="item" effect="dark" content="开启时，允许按设定比例超过需求数量领料出库" placement="top-start">
                <i class="el-icon-info"></i>
              </el-tooltip>
              <span>&nbsp;允许超领:</span>
            </template>
            <template slot-scope="{}" slot="overCollarMentRatio">
              <div>
                <el-radio v-model="formData[index].constraintOperator" label="=" disabled>不限制</el-radio>
                <el-radio v-model="formData[index].constraintOperator" label=">" disabled
                  >允许超领（订单数量）比例:
                  <el-input style="width: 40%" disabled class="overpaymentRatio-value" v-model="formData[index].constraintValue" type="number" min="1" placeholder=""></el-input>
                  %</el-radio
                >
              </div>
            </template>
          </avue-form>
        </div>
      </div>
    </template>
    <div class="add-btn" v-if="dialogType === 'edit'">
      <el-button type="text" size="small" icon="el-icon-circle-plus-outline" @click="handleAdd()" class="btn-add">添加规则</el-button>
    </div>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows"></common-modal-template>
  </div>
</template>

<script>
import { getList as getMsdList, getLevelsList } from '@/api/product/msd/grade';
import { getCategory, getRulesName } from '@/api/warehouse/materialRules';
import commonModalTemplate from '@/components/common-modal-template/common-modal-template';
export default {
  name: 'ruleContent',
  components: {
    commonModalTemplate
  },
  props: {
    ruleType: {
      type: String,
      default: ''
    },
    dialogType: {
      type: String,
      default: ''
    },
    ruleData: {
      type: Object,
      default: () => ({})
    }
  },
  watch: {
    ruleData: {
      handler(val) {
        console.log(this.dialogType);
        if (val.length) {
          this.formatFiled(this._cloneDeep(val));
        }
        if (!val.length && this.dialogType === 'batch') {
          this.formData.push({});
        }
      },
      immediate: true
    }
  },
  data() {
    return {
      msdLevels: [],
      tableOption: {},
      formData: [],
      category: [],
      selectIndex: '-1',
      selectLoading: false,
      rulesOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: '120',
        column: [
          {
            label: '方案名称',
            prop: 'scheme',
            type: 'input',
            span: 8,
            disabled: true,
            order: 3,
            rules: [
              {
                required: true,
                message: '请输入规则名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '规则类型',
            prop: 'type',
            type: 'select',
            dicData: [
              {
                label: '库内管理规则',
                value: 'WAREHOUSE_MANAGE_RULE'
              },
              {
                label: '出库规则',
                value: 'OUTBOUND_RULE'
              },
              {
                label: '收料规则',
                value: 'RECEIVE_RULE'
              }
            ],
            span: 8,
            disabled: true,
            order: 3,
            rules: [
              {
                required: true,
                message: '请输入规则名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '规则名称',
            prop: 'name',
            order: 4,
            span: 8,
            disabled: true,
            hide: true
          },
          {
            label: '',
            prop: 'ruleContainer',
            labelWidth: 0,
            span: 24,
            order: 6,
            formslot: true
          },
          {
            label: '允许超收',
            prop: 'isAllowOverlimit',
            labelslot: true,
            type: 'switch',
            labelTip: '允许超收时将控制该物料收货数量上限',
            order: 6,
            disabled: true,
            align: 'center',
            span: 24,
            dicData: [
              {
                label: '否',
                value: 'false'
              },
              {
                label: '是',
                value: 'true'
              }
            ],
            control: (val, form) => {
              if (form.name === '超收规则') {
                return {
                  isAllowOverlimit: { display: true }
                };
              } else {
                return {
                  isAllowOverlimit: { display: false }
                };
              }
            }
          },
          {
            label: '超收比例',
            prop: 'overlimitRate',
            span: 24,
            labelWidth: 150,
            type: 'radio',
            formslot: true,
            display: false,
            order: 8,
            formatter: (val, value, label) => {
              if (value) {
                return value + '%';
              } else {
                return '';
              }
            },
            control: (val, form) => {
              if (form.name === '超收规则' && form.isAllowOverlimit) {
                return {
                  overlimitRate: { display: true }
                };
              } else {
                return {
                  overlimitRate: { display: false }
                };
              }
            }
          },
          {
            label: '管控先进先出',
            prop: 'fifoRequired',
            type: 'switch',
            value: false,
            align: 'center',
            labelWidth: 150,
            disabled: true,
            dicData: [
              {
                label: '否',
                value: 'false'
              },
              {
                label: '是',
                value: 'true'
              }
            ],
            control: (val, form) => {
              if (form.name === '先进先出') {
                return {
                  fifoRequired: { display: true }
                };
              } else {
                return {
                  fifoRequired: { display: false }
                };
              }
            }
          },
          {
            label: '允许超领',
            prop: 'isAllowOverreceive',
            labelslot: true,
            span: 24,
            type: 'switch',
            labelTip: '允许超领时将控制该物料收货数量上限',
            value: false,
            hide: true,
            disabled: true,
            dicData: [
              {
                label: '否',
                value: 'false'
              },
              {
                label: '是',
                value: 'true'
              }
            ],
            control: (val, form) => {
              if (form.name === '超领规则') {
                return {
                  isAllowOverreceive: { display: true }
                };
              } else {
                return {
                  isAllowOverreceive: { display: false }
                };
              }
            }
          },
          {
            label: '超领比例',
            prop: 'overCollarMentRatio',
            span: 24,
            labelWidth: 150,
            type: 'radio',
            formslot: true,
            display: false,
            control: (val, form) => {
              if (form.name === '超领规则' && form.isAllowOverreceive === true) {
                return {
                  overCollarMentRatio: { display: true }
                };
              } else {
                return {
                  overCollarMentRatio: { display: false }
                };
              }
            }
          },
          {
            label: '保质期天数',
            prop: 'expirationDays',
            min: 0,
            span: 10,
            precision: 0,
            type: 'number',
            disabled: true,
            control: (val, form) => {
              if (form.name === '保质期天数') {
                return {
                  expirationDays: { display: true }
                };
              } else {
                return {
                  expirationDays: { display: false }
                };
              }
            }
          },
          {
            label: '保质期预警提前天数',
            prop: 'expirationWarningDays',
            min: 0,
            span: 10,
            precision: 0,
            labelWidth: 150,
            type: 'number',
            disabled: true,
            control: (val, form) => {
              if (form.name === '保质期预警天数') {
                return {
                  expirationWarningDays: { display: true }
                };
              } else {
                return {
                  expirationWarningDays: { display: false }
                };
              }
            }
          }
        ]
      },
      ruleCategoryOption: [],
      relationIds: [],
      fifoControlPart: ''
    };
  },
  methods: {
    handleDelete(index) {
      if (this.formData[index].id) {
        this.relationIds.push(this.formData[index].id);
      }
      this.formData.splice(index, 1);
    },
    async getRuleCategoryData(val, index) {
      try {
        const ruleCategoryName = this.category.filter((item) => item.value === val)[0].label;
        const form = Object.assign(this.formData[index], {
          name: '',
          code: '',
          remark: '',
          ruleCategoryName,
          businessRuleTypeName: this.formData[index].$businessRuleType
        });
        this.formData.splice(index, 1, form);
        this.selectLoading = true;
        const res = await getRulesName({ businessRuleType: this.ruleType, ruleCategory: val });
        this.ruleCategoryOption = res.data.data || [];
      } catch (e) {
        console.warn(e);
      } finally {
        this.selectLoading = false;
      }
    },
    formatFiled(data = []) {
      data.forEach((item) => {
        if (item.name === '保质期天数') {
          item.expirationDays = item.constraintValue;
          delete item.constraintValue;
        } else if (item.name === '保质期预警天数') {
          item.expirationWarningDays = item.constraintValue;
          delete item.constraintValue;
        } else if (item.name === '先进先出') {
          item.fifoRequired = item.constraintValue;
          delete item.constraintValue;
        } else if (item.name === '超收规则') {
          item.isAllowOverlimit = !!item.constraintValue;
        } else if (item.name === '超领规则') {
          item.isAllowOverreceive = !!item.constraintValue;
        }
      });
      this.formData = data;
    },
    handleAdd() {
      const businessRuleTypeMap = {};
      this.formData.push({});
    },
    getSelectedRows(rowData) {
      const form = {
        id: rowData.id,
        code: rowData.code,
        name: rowData.name,
        type: rowData.type,
        ...rowData
      };
      //字段转化
      if (form.name === '保质期天数') {
        form.expirationDays = form.constraintValue;
        delete form.constraintValue;
      } else if (form.name === '保质期预警天数') {
        form.expirationWarningDays = form.constraintValue;
        delete form.constraintValue;
      } else if (form.name === '先进先出') {
        form.fifoRequired = form.constraintValue;
        delete form.constraintValue;
      } else if (form.name === '超收规则') {
        form.isAllowOverlimit = !!form.constraintValue;
      } else if (form.name === '超领规则') {
        form.isAllowOverreceive = !!form.constraintValue;
      }

      this.formData.splice(this.selectIndex, 1, form);
    },
    //选择规则分类
    openRulesModel(index) {
      this.selectIndex = index;
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择方案',
        url: `/api/mes-warehouse/rule-scheme/page`,
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '方案名称',
            prop: 'scheme',
            search: true
          },
          {
            label: '规则类型',
            prop: 'type'
            // formatter: (val, value, label) => {
            //   const fieldMap = {
            //     WAREHOUSE_MANAGE_RULE: '库内管理规则',
            //     OUTBOUND_RULE: '出库规则',
            //     RECEIVE_RULE: '收料规则'
            //   };
            //   return fieldMap[val.type];
            // }
          },
          {
            label: '规则名称',
            prop: 'name',
            type: 'select'
          },
          {
            label: '备注',
            prop: 'remark'
          }
        ]
      };
    }
  }
};
</script>

<style scoped lang="scss">
.form-content {
  position: relative;
  margin-top: 12px;
}
.btn-danger {
  position: absolute;
  right: 12px;
  z-index: 99;
  .btn-del {
    color: #f56c6c;
  }
}
.rules-content {
  border: 1px solid #c0c4cc;
  padding: 24px 16px;
  h3 {
    margin: 0;
  }
}
.add-btn {
  text-align: center;
  .btn-add {
    font-size: 16px;
  }
}
</style>
